<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<style>
		img {
			position: absolute;
			top: 300px; left: 300px;
		}
		#box {
			position: absolute;
			top: 0; left: 0;
			width: 100px; height: 100px;
			background: #58a;
		}
	</style>
</head>
<body>
	<img src="1.jpg" alt="">
	<div id="box"></div>
	<script>
		var oImg = document.querySelector('img');
		var oBox = document.querySelector('div');
		drag (oBox);
		function drag (obj) {
			obj.onmousedown = function (ev) {
				var ev = ev || window.ev;
				var x = ev.clientX - obj.offsetLeft;
				var y = ev.clientY - obj.offsetTop;

				if (obj.setCapture) {
					obj.setCapture();
				}

				document.onmousemove = function (ev) {

					var ev = ev || window.event;
					var targetY = ev.clientY - y;
					var targetX = ev.clientX - x;

					// 左侧的判断条件
					var cdtL = oImg.offsetLeft - oBox.offsetWidth;
					// 右侧的判断条件
					var cdtR = oImg.offsetLeft + oImg.offsetWidth;
					// 上侧的判断条件
					var cdtT = oImg.offsetTop - oBox.offsetHeight;
					// 下侧的判断条件
					var cdtB = oImg.offsetTop + oImg.offsetHeight;

					if (cdtL < targetX && targetX < cdtR && cdtT < targetY && targetY < cdtB) {
						oImg.src = '2.jpg';
					} else {
						oImg.src = '1.jpg';
					};

					obj.style.top = targetY + 'px';
					obj.style.left = targetX + 'px';

					return false;
				}

				document.onmouseup = function () {

					document.onmousemove = document.onmouseup = null;

					if (obj.setCapture) {
						obj.releaseCapture();
					}
				}
			}
		}
	</script>
</body>
</html>